import { useEffect, useState, Suspense } from 'react'
import { Outlet, useNavigate } from 'react-router'

import { Menu, ConfigProvider, Image, Popover, Typography, Breadcrumb, message } from "antd";
import { AreaChartOutlined, UserSwitchOutlined, FormOutlined, EnvironmentOutlined, HomeOutlined, AlertOutlined, UserOutlined, ShopOutlined } from '@ant-design/icons';

import logo from '../../res/logo.png'
import QuitPopover from '../../component/quitPopover'
import PageLoading from '../../component/pageLoading'

import { jumpTo } from '../../utils/jump'

//缓存
import { putCache, getCache } from '../../utils/cache'
import { current_menu_sub_item_key, current_menu_item_key } from '../../utils/cache/cacheKey'
//api
import { getUserBaseInfo } from '../../utils/axiosRequest/api'


import styles from './index.module.css'


function Main() {
    const { Text } = Typography;

    const items = [
        { key: '0', icon: <AreaChartOutlined />, label: '统计分析' },
        {
            key: '1', icon: <UserSwitchOutlined />, label: '人员管理',
            children: [
                { key: '17', label: '查询用户' },
            ],
        },
        {
            key: '2', icon: <EnvironmentOutlined />, label: '网点管理',
            children: [
                { key: '25', label: '查询网点' },
            ],

        },
        {
            key: '3', icon: <AlertOutlined />, label: '风险库',
            children: [
                { key: '246', label: '取现记录' },
                { key: '215', label: '导入文件' },
            ],

        },
        { key: '4', icon: <FormOutlined />, label: '高级功能' },
    ];



    //消息提示
    const [messageApi, contextHolder] = message.useMessage();
    //导航
    const navigate = useNavigate()
    //注销登录框
    const [isPopoverOpen, setPopoverOpen] = useState(false);
    //当前选中的itemKey
    const [itemKey, setItemKey] = useState(() => {
        return getCache(current_menu_item_key, '0');
    });
    //当前选中的父itemKey
    const [subItemKey, setSubItemKey] = useState(() => {
        return getCache(current_menu_sub_item_key, '0');
    });
    //默认打开的父itemKey
    const [stateOpenKeys, setStateOpenKeys] = useState([]);
    //用户名字
    const [userName, setUserName] = useState('用户名：---');
    //网点
    const [branch, setBranch] = useState('---');

    //[]空数组相当于componentDidMount
    useEffect(() => {
        //页面刷新后，自动展开父组item
        const timer = setTimeout(() => {
            onOpenChange([subItemKey])
        }, 500);
        return () => {
            clearTimeout(timer);
        }
    }, []);

    //监听itemKey的状态
    useEffect(() => {
        putCache(current_menu_item_key, itemKey, '0');
    }, [itemKey]);

    //监听subItemKey的状态
    useEffect(() => {
        putCache(current_menu_sub_item_key, subItemKey, '0');
    }, [subItemKey]);

    //[]空数组相当于componentDidMount
    useEffect(() => {
        initData()
        return () => {
        }
    }, []);

    function initData() {
        //获取用户基础信息
        const params = new Map()
        getUserBaseInfo(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    const respData = data.data;
                    setUserName(respData.userName)
                    setBranch(respData.branName)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    function handleOpenChange(newOpen) {
        setPopoverOpen(newOpen);
    };

    function functionPopoverCancel() {
        setPopoverOpen(false);
    };


    function getLevelKeys(items1) {
        const key = {};
        const func = (items2, level = 1) => {
            items2.forEach(item => {
                if (item.key) {
                    key[item.key] = level;
                }
                if (item.children) {
                    func(item.children, level + 1);
                }
            });
        };
        func(items1);
        return key;
    };
    const levelKeys = getLevelKeys(items);


    function onOpenChange(openKeys) {
        const currentOpenKey = openKeys.find(key => stateOpenKeys.indexOf(key) === -1);
        // open
        if (currentOpenKey !== undefined) {
            const repeatIndex = openKeys
                .filter(key => key !== currentOpenKey)
                .findIndex(key => levelKeys[key] === levelKeys[currentOpenKey]);
            setStateOpenKeys(
                openKeys
                    // remove repeat key
                    .filter((_, index) => index !== repeatIndex)
                    // remove current level all child
                    .filter(key => levelKeys[key] <= levelKeys[currentOpenKey]),
            );

        } else {
            // close
            setStateOpenKeys(openKeys);
        }
    };

    function selectItem({ key, keyPath }) {
        setSubItemKey(keyPath[keyPath.length - 1])//数组最后一个元素
        setItemKey(key)
        switch (key) {
            case '0':
                //统计分析
                jumpTo(navigate, '/main/statistic', true, null)
                break;

            case '17':
                //人员管理
                jumpTo(navigate, '/main/personnel', true, null)
                break;

            case '25':
                //网点查看
                jumpTo(navigate, '/main/branch', true, null)
                break;

            case '246':
                //取现记录
                jumpTo(navigate, '/main/takeRecord', true, null)
                break;

            case '215':
                //风险库查看
                jumpTo(navigate, '/main/uploadRiskFile', true, null)
                break;

            case '4':
                //其他设置
                jumpTo(navigate, '/main/advancedSetting', true, null)
                break;

            default:
                messageApi.open({ type: 'error', content: '该模块建设中' });
                break;
        }
    }

    return (
        <ConfigProvider theme={{
            components: {
                Menu: {
                    // fontSize:'1',
                    fontSizeLG: '1',
                    itemSelectedColor: '#ffffff',
                    itemSelectedBg: "#1677ff",
                },
            }
        }}>
            <div className={styles.container}>
                {contextHolder}
                <div className={styles.left_menu_box}>
                    <div className={styles.left_menu_head}>
                        <Image preview={false} width={25} src={logo} />
                        <span className={styles.left_menu_head_title}>管理平台</span>
                    </div>
                    <Menu className={styles.left_menu}
                        defaultSelectedKeys={[itemKey]}
                        onSelect={selectItem}
                        openKeys={stateOpenKeys}
                        onOpenChange={onOpenChange}
                        mode="inline"
                        theme="light"
                        items={items}
                    />
                    <div className={styles.left_menu_bottom}>
                        <span className={styles.left_menu_bottom_title}>version:1.0.7</span>
                    </div>
                </div>

                <div className={styles.right_container}>
                    <div className={styles.right_head}>
                        <div className={styles.right_breadcrumb_box}>
                            <Breadcrumb separator=">" items={[
                                { title: <><HomeOutlined /><span>管理平台</span></> },
                                { title: <>{items[subItemKey].icon}<span>{items[subItemKey].label}</span></> },
                            ]} />
                        </div>
                        <div className={styles.right_info_box}>
                            <Popover trigger='hover' content={<QuitPopover functionPopoverCancel={functionPopoverCancel} />} open={isPopoverOpen} onOpenChange={handleOpenChange} >
                                <div className={styles.user_name_ico}>
                                    <UserOutlined />
                                    <Text code>{userName}</Text>
                                </div>
                            </Popover>
                            <div className={styles.branch}>
                                <ShopOutlined />
                                <Text code>{branch}</Text>
                            </div>
                        </div>
                    </div>

                    <div className={styles.right_content}>
                        <Suspense fallback={<PageLoading />}>
                            <Outlet ></Outlet>
                        </Suspense>
                    </div>
                </div>

            </div>
        </ConfigProvider>

    )
}

export default Main;